package com.hshx.controller;

import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import com.baomidou.mybatisplus.annotation.OrderBy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hshx.VO.UsersVo;
import com.hshx.client.Job_classificationClient;
import com.hshx.client.SalaryClient;
import com.hshx.pojo.Job_classification;
import com.hshx.pojo.Role;
import com.hshx.pojo.Users;
import com.hshx.service.*;
//import com.hshx.shiro.MD5Pwd;
//import com.hshx.util.RedisUtil;
import com.hshx.shiro.MD5Pwd;
import com.hshx.util.RedisUtil1;
import io.swagger.annotations.*;
import org.apache.catalina.User;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RequestMapping("/systemService")
@Api(tags="用户管理")
@RestController
public class UsersController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private PositionService positionService;
    @Resource
    private SalaryClient salaryClient;
    @Autowired
    private RedisUtil1 redisUtil1;
    @Autowired
    private IMessageProduceService service;

    private Object obj;

    /**
     * 查询所有用户
     */
    @GetMapping("/getUsersList")
    public List<Users> getUsersList(){
        return usersService.list();
    }

    /**
     * 单个用户的添加
     * @param users
     * @return
     */
    @PostMapping("/addUsers")
    public boolean addUsers(@SpringQueryMap Users users){
        if(users.getUsers_entryDate()==null){
            users.setUsers_entryDate(new Date());
        }
        //判断数据有效性[角色]
        //该角色被禁用
        if(roleService.getById(users.getUsers_role()).getRole_state()==2){
            return false;
        }

        users.setPassword(MD5Pwd.MD5Pwd(users.getUsername(),users.getPassword()));
        if(usersService.save(users)){
            this.service.send("direct","flushUsers","removeUsers");
            return true;
        }
        return false;
    }

    /**
     * 某个用户信息修改
     * @return
     */
    @PostMapping("/updateUsers")
    public boolean updateUsers(@SpringQueryMap Users users,HttpSession session){
        System.out.println(users);
        if("".equals(users.getPassword())||"undefined".equals(users.getPassword())){
            users.setPassword(null);
        }
        //判断数据有效性[角色,部门，职位，薪资标准]
        //该角色被禁用
        if(users.getUsers_role()!=null&&roleService.getById(users.getUsers_role()).getRole_state()==2){
            return false;
        }
        //该部门被禁用
        if(users.getUsers_dept()!=null&&deptService.getById(users.getUsers_dept()).getDept_state()==2){
            return false;
        }
        //该职位被禁用
        if(users.getUsers_position()!=null&&positionService.getById(users.getUsers_position()).getPosition_state()==2){
            return false;
        }
        //该薪资标准被禁用
        if(users.getUsers_salary()!=null&&salaryClient.salaryID(users.getUsers_salary()).getSalary_state()==0){
            return false;
        }

        if(usersService.updateById(users)){
            this.service.send("direct","flushUsers","removeUsers");
            return true;
        }
        return false;
    }

    /**
     * 登录(查询某个用户信息)
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/getUsersOne")
    public Map<String,Object> getUsers(String username, String password){
        Map<String, Object> map = new HashMap<>();
//        System.out.println("username:"+username+"\tpassword:"+password);
        String MD5Oassword=MD5Pwd.MD5Pwd(username,password);
        Users user=usersService.getOne(new QueryWrapper<Users>().eq("username",username).eq("password",MD5Oassword));
        if(user==null||user.getUsers_id()==0){
            map.put("result",false);
            return map;
        }

        map.put("result",true);
        map.put("username", user.getUsername());
        map.put("role", user.getUsers_role());
        map.put("users_id",user.getUsers_id());
        String token=UUID.randomUUID().toString();
        redisUtil1.set(token,user,60*30L);
        map.put("token",token);
        return map;
    }


    /**
     * 从数据库中移除某个用户
     * @return
     */
    @RequestMapping("/removeUsers")
    public boolean removeUsers(int users_id){
        if(usersService.removeById(users_id)){
            this.service.send("direct","flushUsers","removeUsers");
            return true;
        }
        return false;
    }

    /**
     * 用户批量删除
     * @param idString
     * @return
     */
    @RequestMapping("/removeBatchByIds")
    public boolean removeBatchByIds(String idString){
        if(usersService.removeBatchByIds(Arrays.asList(idString.split(",")))){
            this.service.send("direct","flushUsers","removeBatchByIds");
            return true;
        }
        return false;
    }

    /**
     * 用户组合查询
     * @param pageIndex
     * @param pageSize
     * @param startTime
     * @param endTime
     * @param username
     * @return
     */
    @RequestMapping("/getPage")
    public Map<String,Object> getPage(Integer pageIndex, Integer pageSize,String startTime,String endTime,String username){
        Map<String, Object> userMap = new HashMap<>();
        if(pageIndex==null||pageIndex<=0){
            pageIndex=1;
        }
        if(pageSize==null||pageSize<=0){
            pageSize=10;
        }
        if(username==null){
            username="";
        }
        //先根据参数判断是否查询数据库
        if(((startTime!=null&&startTime!=""&&endTime!=null&&endTime!="")||(username!=null&&username!=""))){
            //参数拼接组合查询
            //查询数据库的情况
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            queryWrapper = queryWrapper.like("username",username)
                    .orderByDesc("users_id");
            if(startTime!=null&&startTime!=""&&endTime!=null&&endTime!=""){
                queryWrapper.between("users_entryDate", startTime, endTime);
            }


            Page<Users> usersPage=PageHelper.startPage(pageIndex,pageSize);
            usersService.list(queryWrapper);
            userMap.put("pageSize",usersPage.getPageSize());
            userMap.put("pages", usersPage.getPages());
            userMap.put("pageNum",usersPage.getPageNum());
            userMap.put("list", usersPage.getResult());
            userMap.put("total", usersPage.getTotal());
        }else{
            //查询redis的情况
            List<Object> objects=redisUtil1.lRange("usersRedisList",0,-1);
            if(objects==null||objects.size()==0){//检查redis中数据失效
                System.out.println("objects==null");
                List<Users> usersList=usersService.list(new QueryWrapper<Users>().orderByDesc("users_id"));
                redisUtil1.lPushAll("usersRedisList",usersList,24*60L);
                userMap.put("pageSize",pageSize);
                userMap.put("pages", usersList.size()%pageSize==0?usersList.size()/pageSize:usersList.size()/pageSize+1);
                userMap.put("pageNum",pageIndex);
                userMap.put("list", usersList.stream().sorted(Comparator.comparing(Users::getUsers_id).reversed()).skip((pageIndex-1)*pageSize).limit(pageSize).collect(Collectors.toList()));
                userMap.put("total", usersList.size());
                return  userMap;
            }else{
                List<Users> usersList=objects.stream().map(o->((Users)o)).collect(Collectors.toList());
                userMap.put("pageSize",pageSize);
                userMap.put("pages", usersList.size()%pageSize==0?usersList.size()/pageSize:usersList.size()/pageSize+1);
                userMap.put("pageNum",pageIndex);
                userMap.put("list", usersList.stream().sorted(Comparator.comparing(Users::getUsers_id).reversed()).skip((pageIndex-1)*pageSize).limit(pageSize).collect(Collectors.toList()));
                userMap.put("total", usersList.size());
                return  userMap;
            }
        }



        return userMap;
    }


    /**
     * 用户名是否被使用
     * @param username
     * @return
     */
    @RequestMapping("/hasUsers")
    public boolean hasUsers(String username){
        return usersService.count(new QueryWrapper<Users>().eq("username",username))>0;
    }

    /**
     * 手机号是否被使用
     * @param phone
     * @return
     */
    @RequestMapping("/hasPhone")
    public boolean hasPhone(String phone){
        return usersService.count(new QueryWrapper<Users>().eq("users_phone",phone))>0;
    }

    /**
     * 身份证号是否被使用
     * @param users_number
     * @return
     */
    @RequestMapping("/hasNumber")
    public boolean hasNumber(String users_number){
        return usersService.count(new QueryWrapper<Users>().eq("users_number",users_number))>0;
    }


    /**
     * 根据用户主键查找某个用户
     * @return
     */
    @RequestMapping("/getUsersById")
    public Users getUsersById(Integer users_id){
//        List<Object> objects=redisUtil1.lRange("usersRedisList",0,-1);
//        if(objects!=null&&objects.size()>0){
//            return objects.stream().map(o->((Users)o)).filter(u->u.getUsers_id()==users_id).findFirst().get();
//        }
        return usersService.getById(users_id);
    }

    /**
     * 根据用户名得到对象
     * @param username
     * @return
     */
    @RequestMapping("/getUserByUsername")
    public Users getUserByUsername(String username){
        return usersService.getOne(new QueryWrapper<Users>().eq("username", username));
    }

    /**
     * 某个薪资标准是否被使用
     * @return
     */
    @RequestMapping("/hasSalary")
    public boolean hasSalary(Integer users_salary){
        return usersService.count(new QueryWrapper<Users>().eq("users_salary", users_salary))>0;
    }

    /**
     * 得到男性员工的数量
     * @return
     */
    @RequestMapping("/getManNumber")
    public long getManNumber(){
        return usersService.count(new QueryWrapper<Users>().eq("gender",1).in("users_state",1,2,3,7));
    }

    /**
     * 得到女性员工的数量
     * @return
     */
    @RequestMapping("/getWomanNumber")
    public long getWomanNumber(){
        return usersService.count(new QueryWrapper<Users>().eq("gender",2).in("users_state",1,2,3,7));
    }

    /**
     * 用户身份
     * @return
     */
    @RequestMapping("/getSessionUsers")
    public Map<String,Object> getSessionUsers(@RequestBody String key){
//        System.out.println(key);
        HashMap<String,Object> map=new HashMap<>();
        if(key==null){
            map.put("status",false);
            return map;
        }
        String token = key.substring(key.indexOf("=")+1);
//        System.out.println("token:"+token);
        Object obj=redisUtil1.get(token);
//        System.out.println("obj:"+redisUtil1.get(token));
        if(obj==null){
           map.put("status",false);
           return map;
        }
        map.put("status", true);
        Users users=(Users) obj;
        redisUtil1.set(token, users, 60 * 30L);
        map.put("username",users.getUsername());
        map.put("role",users.getUsers_role());
        map.put("users_id",users.getUsers_id());
        return map;
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "flushUsers",durable = "true",autoDelete = "true"),
            exchange = @Exchange(value = "direct",type = ExchangeTypes.DIRECT),
            key = "flushUsers"
    ))
    public void flushUsers(String msg){
        System.out.println("========================flushUsersVoRedis====================");
        flushUsersVoRedis();
    }

    /**
     * 更新redis中所有的用户信息
     */
    private void flushUsersVoRedis(){
        redisUtil1.remove("usersRedisList");
        redisUtil1.lPushAll("usersRedisList",usersService.list(new QueryWrapper<Users>().orderByDesc("users_id")),60L*24);
    }

    @RequestMapping("/testSession")
    public String testSession(HttpSession session){
        System.out.println("进入provider");
        String id = session.getId();
        Object uname = session.getAttribute("users");
//        System.out.println(session.toString());
        System.out.println("name:"+session.getAttribute("name"));
        if(session.getAttribute("users")==null){
            System.out.println("此处的session为null");
        }else{
            System.out.println(((Users) session.getAttribute("users")).toString());
        }
        System.out.println("提供者>>>sessionId:"+id+"\t::uname:"+uname);
        return "sesssionId:"+id;
    }



}
